package com.roc.template.cloud.factory.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.roc.template.cloud.CloudConfig;
import com.roc.template.cloud.factory.AccessToken;
import com.roc.template.cloud.util.AccessTokenBean;
import com.roc.template.cloud.util.BasetTokenUtils;
import com.roc.template.cloud.util.HttpClientUtils;
import com.roc.template.exception.BussinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName ResGroupAccessToken
 * @Description: TODO
 * @Author Administrator
 * @Date 2020/7/29 13 43
 * @Version V1.0
 **/
public class ResGroupAccessToken implements AccessToken {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public String accessToken = null;
    public String refreshToken = null;
    public long expiredUntil = 0L;

    private CloudConfig cloudConfig;

    public ResGroupAccessToken(CloudConfig cloudConfig) {
        this.cloudConfig = cloudConfig;
    }


    @Override
    public void getAccesssToken() {
        JSONObject param = new JSONObject();
        param.put("eid", cloudConfig.eid);
        param.put("secret",cloudConfig.secret);
        param.put("timestamp", System.currentTimeMillis());
        param.put("scope","resGroupSecret");

        String url = cloudConfig.outHost+"/gateway/oauth2/token/getAccessToken";
        String retString = HttpClientUtils.post(url, param.toJSONString());

        JSONObject jsonObject = JSON.parseObject(retString);
        AccessTokenBean accessTokenBean = BasetTokenUtils.getParam(jsonObject);
        accessToken = accessTokenBean.getAccessToken();
        refreshToken = accessTokenBean.getRefreshToken();
        expiredUntil = accessTokenBean.getExpiredUntil();
    }

    @Override
    public void refreshAccessToken() {

        JSONObject param = new JSONObject();
        param.put("eid", cloudConfig.eid);
        param.put("refreshToken", refreshToken);
        param.put("timestamp", System.currentTimeMillis());
        param.put("scope", "resGroupSecret");

        String url = cloudConfig.outHost+"/gateway/oauth2/token/refreshToken";
        String retString = HttpClientUtils.post(url, param.toJSONString());

        JSONObject jsonObject = JSON.parseObject(retString);
        logger.info("刷新accessToken:\n" + jsonObject);
        AccessTokenBean accessTokenBean = BasetTokenUtils.getParam(jsonObject);
        accessToken = accessTokenBean.getAccessToken();
        refreshToken = accessTokenBean.getRefreshToken();
        expiredUntil = accessTokenBean.getExpiredUntil();
    }

    @Override
    public void checkAndRefreshAccessToken() {
        if (expiredUntil == 0L) {
            getAccesssToken();
        } else if (expiredUntil< 60L) {
            refreshAccessToken();
        }
    }

    /**
     * 获取所有用户信息
     * @param param
     * @return
     */
    public JSONObject getAllUserInfo(Map<String, Object> param) {
        checkAndRefreshAccessToken();
        Map<String, String> map = new HashMap<>();
        map.put("eid", cloudConfig.eid);
        map.put("nonce", String.valueOf(System.currentTimeMillis()));
        map.put("data", JSON.toJSONString(param));
        String url = cloudConfig.outHost+"/gateway/openimport/open/person/getall?accessToken=";
        url += accessToken;
        String response =null;
        try {
            response = HttpClientUtils.doPost(url, map);
        } catch (Exception e) {
        }
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("获取用户实例:\n" + jsonObject);
        return jsonObject;
    }


    /**
     * 获取用户信息
     * <p>
     * 参考:https://app.lzdcic.com/cloudflow-openplatform/other/3003
     *
     * @param param
     * @return
     */
    public JSONArray getUserInfo(Map<String, Object> param) {
        checkAndRefreshAccessToken();
        Map<String, String> map = new HashMap<>();
        map.put("eid", cloudConfig.eid);
        map.put("nonce", String.valueOf(System.currentTimeMillis()));
        map.put("data", JSON.toJSONString(param));
        String url = cloudConfig.outHost+"/gateway/openimport/open/person/get?accessToken=";
        url += accessToken;
        String response =null;
        try {
            response = HttpClientUtils.doPost(url, map);
        } catch (Exception e) {
        }
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("获取用户实例:\n" + jsonObject);
        if (jsonObject.getBoolean("success")) {
            return jsonObject.getJSONArray("data");
        } else {
            throw new BussinessException(jsonObject.getString("error"));
        }
    }


    /**
     * 获取更新的用户信息
     * @param param
     * @return
     */
    public JSONObject getUpdateUserInfo(Map<String, Object> param) {
        checkAndRefreshAccessToken();
        Map<String, String> map = new HashMap<>();
        map.put("eid", cloudConfig.eid);
        map.put("nonce", String.valueOf(System.currentTimeMillis()));
        map.put("data", JSON.toJSONString(param));
        String url = cloudConfig.outHost+"/gateway/openimport/open/person/getAtTime?accessToken=";
        url += accessToken;
        String response =null;
        try {
            response =  HttpClientUtils.doPost(url, map);
        } catch (Exception e) {
        }
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("获取用户实例:\n" + jsonObject);
        return jsonObject;
    }

}
